var ns, printModule, BluetoothPrinter, bluePrinter, xGprinterPlus, myConnectInterval = null;
app = new Vue({
    el: '#app',
    data: {
        printId: 0,
        deviceList: [],
        form: {
            name: '',
            address: ''
        },
        list: [],
        connect_id: '',
        connect_label: '',
        getDeviceStatus: 0, //0=未获取 1=获取失败 2=获取成功
        checkStatusCount: 0,
        lastDevice: null,
        connectCount: 1,
        issearch: false
    },
    methods: {
        get_data: function () {
            var that = this;
            that.issearch = false;
            ns.get({
                action: 'getprintdeviceroomfeehistory',
                printId: that.printId
            }, function (succeed, data, err) {
                that.issearch = true;
                if (succeed) {
                    that.list = data;
                }
                else {
                    api.toast({
                        msg: err
                    })
                }
                that.get_list();
            });
        },
        checkScanStatus() {
            var that = this;
            that.checkStatusCount++;
            if (that.getDeviceStatus == 2) {
                return;
            }
            if (that.checkStatusCount > 3) {
                that.getDeviceStatus = 1;
                return
            }
            setTimeout(function () {
                that.checkScanStatus();
            }, 2000)
        },
        get_list: function () {
            var that = this;
            var lastDevice = api.getPrefs({
                sync: true,
                key: 'last_print_device'
            });
            if (lastDevice) {
                that.lastDevice = eval('(' + lastDevice + ')');
            }
            that.getDeviceStatus = 0;
            that.deviceList = [];
            if (api.systemType == 'ios') {
                bluePrinter.scan(function (ret, err) {
                    if (ret.peripheral) {
                        var myIndex = that.deviceList.findIndex(myItem => myItem.id == ret.peripheral.id)
                        if (myIndex == -1) {
                            that.deviceList.push(ret.peripheral);
                        }
                        if (that.lastDevice) {
                            if (ret.peripheral.name == that.lastDevice.name) {
                                setTimeout(function () {
                                    that.do_connect(that.lastDevice);
                                }, 1000)
                            }
                        }
                    }
                    that.getDeviceStatus = 2;
                });
                that.checkScanStatus();
                return;
            }
            if (that.lastDevice && that.lastDevice.macAddress) {
                xGprinterPlus.connectBleByMacAddress({
                    macAddress: that.lastDevice.macAddress
                }, function (ret, err) {
                    if (!ret.status) {
                        that.connectDevices()
                        return
                    }
                    that.form.name = that.lastDevice.macAddress;
                    that.connect_label = '已连接设备' + that.lastDevice.macAddress

                });
                return
            }
            that.connectDevices()
        },
        connectDevices() {
            var that = this
            xGprinterPlus.connectDevices(function (ret, err) {
                if (ret.status) {
                    api.setPrefs({
                        key: 'last_print_device',
                        value: JSON.stringify(ret.data)
                    });
                    that.form.name = ret.data.macAddress;
                    that.connect_label = '已连接设备' + ret.data.macAddress
                }
            });
        },
        do_connect: function (item) {
            var that = this;
            that.do_connect_process(item);
            myConnectInterval = setInterval(function () {
                that.do_connect_process(item);
            }, 10000);
        },
        do_connect_process: function (item) {
            if (!item) {
                return
            }
            var that = this;
            that.connect_label = '连接中...';
            that.form.name = '';
            setTimeout(() => {
                if (api.systemType == 'ios') {
                    bluePrinter.connect({
                        id: item.id
                    }, function (ret, err) {
                        if (myConnectInterval != null) {
                            clearInterval(myConnectInterval);
                            myConnectInterval = null;
                        }
                        if (ret.status) {
                            that.connect_label = '已连接设备' + item.name
                            that.form.name = item.name;
                            api.setPrefs({
                                key: 'last_print_device',
                                value: JSON.stringify(item)
                            });
                        } else {
                            that.form.name = '';
                            that.connect_label = '连接失败，请重试'
                        }
                        api.toast({
                            msg: that.connect_label
                        })
                    });
                    return
                }
                moduleJiaBo.connect({ address: item.address }, function (ret, err) {
                    console.log(JSON.stringify(ret));
                    that.form.name = item.name;
                    that.connect_label = '已连接设备' + item.name
                });

            }, 100);
        },
        do_print() {
            var that = this;
            if (!that.form.name) {
                api.toast({
                    msg: '请选择打印机'
                })
                return;
            }
            var dataList = that.list;
            api.confirm({
                title: '提示',
                msg: '确认打印？',
                buttons: ['确认', '取消']
            }, function (ret, err) {
                if (1 == ret.buttonIndex) {
                    if (api.systemType == 'ios') {
                        bluePrinter.appendCleare();
                        bluePrinter.appendTitle({
                            string: '收款凭证'
                        })
                        dataList.forEach(item => {
                            var myMsg = item.title;
                            if (item.value) {
                                myMsg += item.value;
                            }
                            bluePrinter.appendText({
                                title: myMsg
                            })
                        })
                        bluePrinter.appendText({
                            title: '',
                        })
                        bluePrinter.printString(function (ret, err) {
                            if (err) {
                                api.toast({
                                    msg: err
                                })
                            }
                        });
                        return
                    }
                    var rows = []
                    //设置打印居中
                    rows.push({
                        lineType: 'align',
                        data: 'center'
                    })
                    //字体 是否加粗 倍高 倍宽 下划线
                    rows.push({
                        lineType: 'style',
                        data: [0, 1, 0, 0, 0]
                    })
                    rows.push({
                        lineType: 'text',
                        data: '收款单据\n'
                    })
                    rows.push({
                        lineType: 'align',
                        data: 'left'
                    })
                    rows.push({
                        lineType: 'style',
                        data: [0, 0, 0, 0, 0]
                    })
                    dataList.forEach(item => {
                        var msg = item.title;
                        if (item.value) {
                            msg += item.value;
                        }
                        rows.push({
                            lineType: 'text',
                            data: msg + '\n'
                        })
                    })
                    rows.push({
                        lineType: 'lines',
                        data: 3
                    })
                    xGprinterPlus.printReceipt({
                        rows: rows
                    }, function (ret, err) {
                        if (!ret.status && err) {
                            api.toast({
                                msg: err
                            })
                        }
                    });
                }
            });
        },
        get_list_bak: function () {
            var that = this;
            var lastDevice = api.getPrefs({
                sync: true,
                key: 'last_print_device'
            });
            if (lastDevice) {
                that.lastDevice = eval('(' + lastDevice + ')');
            }
            that.getDeviceStatus = 0;
            that.deviceList = [];
            if (api.systemType == 'ios') {
                bluePrinter.scan(function (ret, err) {
                    if (ret.peripheral) {
                        var myIndex = that.deviceList.findIndex(myItem => myItem.id == ret.peripheral.id)
                        if (myIndex == -1) {
                            that.deviceList.push(ret.peripheral);
                        }
                        if (that.lastDevice) {
                            if (ret.peripheral.name == that.lastDevice.name) {
                                setTimeout(function () {
                                    that.do_connect(that.lastDevice);
                                }, 1000)
                            }
                        }
                    }
                    that.getDeviceStatus = 2;
                });
                that.checkScanStatus();
                return;
            }
            BluetoothPrinter.scan({}, function (ret, err) {
                if (ret.status) {
                    BluetoothPrinter.listBT({}, function (ret2, err) {
                        BluetoothPrinter.cancelScan({}, function (ret3, err3) {
                        })
                        that.deviceList = ret2;
                        if (that.lastDevice) {
                            that.deviceList.forEach(myItem => {
                                if (myItem.name == that.lastDevice.name) {
                                    setTimeout(function () {
                                        that.do_connect(that.lastDevice);
                                    }, 1000)
                                }
                            })
                        }
                    })
                }
                else {
                    api.toast({
                        msg: JSON.stringify(err)
                    })
                }
            })
        },
        handleOnClick: function (item) {
            var that = this;
            that.connectCount = 1;
            that.do_connect(item);
        },
        do_connect_bak: function (item) {
            var that = this;
            that.do_connect_process(item);
            myConnectInterval = setInterval(function () {
                that.do_connect_process(item);
            }, 10000);
        },
        do_connect_process_bak: function (item) {
            if (!item) {
                return
            }
            var that = this;
            that.connect_label = '连接中...';
            that.form.name = '';
            setTimeout(() => {
                if (api.systemType == 'ios') {
                    bluePrinter.connect({
                        id: item.id
                    }, function (ret, err) {
                        if (myConnectInterval != null) {
                            clearInterval(myConnectInterval);
                            myConnectInterval = null;
                        }
                        if (ret.status) {
                            that.connect_label = '已连接设备' + item.name
                            that.form.name = item.name;
                            api.setPrefs({
                                key: 'last_print_device',
                                value: JSON.stringify(item)
                            });
                        } else {
                            that.form.name = '';
                            that.connect_label = '连接失败，请重试'
                        }
                        api.toast({
                            msg: that.connect_label
                        })
                    });
                    return
                }
                BluetoothPrinter.disconnectBT({
                }, function (ret0, err0) {
                    BluetoothPrinter.connect({
                        name: item.name
                    }, function (ret, err) {
                        if (myConnectInterval != null) {
                            clearInterval(myConnectInterval);
                            myConnectInterval = null;
                        }
                        if (ret.status) {
                            that.connect_label = '已连接设备' + item.name
                            that.form.name = item.name;
                            api.setPrefs({
                                key: 'last_print_device',
                                value: JSON.stringify(item)
                            });
                        } else {
                            that.connect_label = '连接失败';
                            if (that.connectCount >= 3) {
                                api.toast({
                                    msg: that.connect_label
                                })
                                return;
                            }
                            that.connectCount++;
                            that.connect_label = '连接失败，尝试第' + that.connectCount + '次连接';
                            setTimeout(function () {
                                that.do_connect(item);
                            }, 1000)
                            return;
                        }
                        api.toast({
                            msg: that.connect_label
                        })
                    });
                });

            }, 100);
        },
        do_print_bak() {
            var that = this;
            if (!that.form.name) {
                api.toast({
                    msg: '请选择打印机'
                })
                return;
            }
            var dataList = that.list;
            api.confirm({
                title: '提示',
                msg: '确认打印？',
                buttons: ['确认', '取消']
            }, function (ret, err) {
                if (1 == ret.buttonIndex) {
                    if (api.systemType == 'ios') {
                        bluePrinter.appendCleare();
                        bluePrinter.appendTitle({
                            string: '收款凭证'
                        })
                        dataList.forEach(item => {
                            var myMsg = item.title;
                            if (item.value) {
                                myMsg += item.value;
                            }
                            bluePrinter.appendText({
                                title: myMsg
                            })
                        })
                        bluePrinter.appendText({
                            title: '',
                        })
                        bluePrinter.printString(function (ret, err) {
                            if (err) {
                                api.toast({
                                    msg: err
                                })
                            }
                        });
                        return
                    }
                    var msg = String.fromCharCode(27) + String.fromCharCode(97) + String.fromCharCode(1) + //居中
                        String.fromCharCode(27) + String.fromCharCode(33) + String.fromCharCode(0) +//字体大小
                        String.fromCharCode(27) + String.fromCharCode(51) + String.fromCharCode(25) +//行高
                        "收款凭证\n" +
                        String.fromCharCode(27) + String.fromCharCode(97) + String.fromCharCode(0) + //靠左
                        String.fromCharCode(27) + String.fromCharCode(33) + String.fromCharCode(0) + //字体大小
                        String.fromCharCode(27) + String.fromCharCode(51) + String.fromCharCode(20); //行高
                    dataList.forEach(item => {
                        msg += item.title;
                        if (item.value) {
                            msg += item.value;
                        }
                        msg += '\n';
                    })
                    msg += "\n\n";
                    BluetoothPrinter.printPOSCommand({
                        msg: msg
                    }, function (ret, err) {
                        if (ret.status) {
                            api.toast({
                                msg: '正在打印'
                            })
                        }
                        else {
                            api.toast({
                                // msg: '打印失败，请重新连接打印机'
                                msg: err
                            })
                        }
                    });
                }
            });

        }
    }
});
apiready = function () {
    api.parseTapmode();
    printModule = api.require('posPrinter');
    BluetoothPrinter = api.require('djyPrinter');
    bluePrinter = api.require('bluePrinter');
    xGprinterPlus = api.require('xGprinterPlus');
    ns = window.Foresight.Util;
    app.printId = api.pageParam.printId;
    app.get_data();
};
